﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace dlgcy
{
    public partial class MainForm : Form
    {
        private string _punctuation;// 输入/选取 的字符；
        private string _signLeft;
        private string _signRight;
        private string _str;

        private string _fileName = ""; //当前编辑的文件名；
        private int _findPostion = 0;  //查找与替换中的位置；
        private bool _needSave = false;

        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            InitComboBox();
            CheckIsTopMost();
        }

        private void InitComboBox()
        {
            if (radioAdd.Checked)
                _punctuation = comboBox_add.Text;
            else
                _punctuation = comboBox_remove.Text;

            SplitPunctuation();
        }

        private void SplitPunctuation()
        {
            int num = _punctuation.Length;
            _signLeft = _punctuation.Substring(0, num / 2);
            _signRight = _punctuation.Substring(num / 2, num - num / 2);
        }

        #region 窗口|菜单 相关

        #region 编辑

        /// <summary>
        /// 剪切
        /// </summary>
        private void MenuItemEditCut_Click(object sender, EventArgs e)
        {
            richTextBox1.Cut();
        }

        /// <summary>
        /// 复制
        /// </summary>
        private void MenuItemEditCopy_Click(object sender, EventArgs e)
        {
            richTextBox1.Copy();
        }

        /// <summary>
        /// 粘贴
        /// </summary>
        private void MenuItemEditPaste_Click(object sender, EventArgs e)
        {
            richTextBox1.Paste();
        }

        /// <summary>
        /// 撤销
        /// </summary>
        private void MenuItemEditUndo_Click(object sender, EventArgs e)
        {
            richTextBox1.Undo();
        }

        /// <summary>
        /// 恢复
        /// </summary>
        private void MenuItemEditRedo_Click(object sender, EventArgs e)
        {
            richTextBox1.Redo();
        }

        /// <summary>
        /// 粘贴为纯文本
        /// </summary>
        private void MenuItemEditPastePure_Click(object sender, EventArgs e)
        {
            richTextBox1.Paste(DataFormats.GetFormat(DataFormats.UnicodeText));
        }

        #endregion

        private void MenuItemFileNew_Click(object sender, EventArgs e)
        {
            //新建文件菜单项
            if (!SaveOldFile()) //如果返回false本次操作取消
                return;
            richTextBox1.Text = ""; //或richTextBox1.Clear();
            _fileName = ""; //新建文件没有文件名。 
        }

        private void MenuItemFileOpen_Click(object sender, EventArgs e)
        {
            //打开文件菜单项
            if (!SaveOldFile()) //如果返回false本次操作取消
                return;
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                _fileName = openFileDialog1.FileName;
                richTextBox1.LoadFile(openFileDialog1.FileName, RichTextBoxStreamType.PlainText);
            }
        }

        private void MenuItemFileSave_Click(object sender, EventArgs e)
        {
            //保存文件菜单项
            if (_fileName.Length != 0)
            {
                _needSave = false;
                richTextBox1.SaveFile(_fileName, RichTextBoxStreamType.PlainText);
            }
            else
                SaveAsNewFile();
        }

        private void MenuItemFileSaveAs_Click(object sender, EventArgs e)
        {
            //另存为菜单项
            SaveAsNewFile();
        }

        /// <summary>
        /// 另存为
        /// </summary>
        private void SaveAsNewFile()
        {
            //存储新文件；
            //SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                _fileName = saveFileDialog1.FileName;
                richTextBox1.SaveFile(_fileName, RichTextBoxStreamType.PlainText);
                _needSave = false;
            }
        }

        private void MenuItemExit_Click(object sender, EventArgs e)
        {
            //退出菜单项 
            Close();
        }

        private void MenuItemAbout_Click(object sender, EventArgs e)
        {
            //关于菜单项
            AboutBox AboutDialog = new AboutBox();
            AboutDialog.ShowDialog(this); //打开模式对话框
        }

        private void MenuItemFindReplace_Click(object sender, EventArgs e)
        {
            //查找与替换菜单项；
            _findPostion = 0;
            formFindReplace FindReplaceDialog = new formFindReplace(this);
            FindReplaceDialog.Show();
        }

        public void FindRichTextBoxString(string FindString)
        {
            if (_findPostion >= richTextBox1.Text.Length)
            {
                MessageBox.Show("已到文本底部,再次查找将从文本开始处查找", "提示", MessageBoxButtons.OK);
                _findPostion = 0; //下次查找的开始位置
                return;
            }
            //查找；
            _findPostion = richTextBox1.Find(FindString, _findPostion, RichTextBoxFinds.MatchCase);
            if (_findPostion == -1) //-1表示未找到匹配字符串，提示用户
            {
                MessageBox.Show("未找到匹配字符串,再次查找将从文本开始处查找", "提示", MessageBoxButtons.OK);
                _findPostion = 0; //下次查找的开始位置
            }
            else //找到匹配字符串
            {
                richTextBox1.Focus(); //主窗体成为注视窗口
                _findPostion += FindString.Length; //下次查找的开始位置在此次找到字符串之后
            }
        }

        public void ReplaceRichTextBoxString(string replaceString)
        {
            if (richTextBox1.SelectedText.Length != 0)
                richTextBox1.SelectedText = replaceString; //替换被选定的字符串 
        }

        public void ReplaceRichTextBoxStringAll(string searchStr, string replaceStr)
        {
            richTextBox1.SelectAll();

            richTextBox1.SelectedText = richTextBox1.SelectedText.Replace(searchStr, replaceStr);
        }

        /// <summary>
        /// 保存旧文件
        /// </summary>
        /// <returns>true-用户选择了保存或不保存，false-用户选择了取消</returns>
        public bool SaveOldFile()
        {
            bool result = true;
            if (_needSave)
            {
                var dr = MessageBox.Show(this, "要保存当前更改吗？", "保存更改吗？", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                switch (dr) //根据用户选择做相应处理
                {
                    case DialogResult.Yes:
                        _needSave = false; //保存文件后，应使needSave为false
                        if (_fileName.Length != 0)
                            richTextBox1.SaveFile(_fileName, RichTextBoxStreamType.PlainText);
                        else
                        {
                            SaveAsNewFile();
                        } //返回true通知调用本方法的程序本次操作继续
                        result = true;
                        break;
                    //单击了no按钮，不保存
                    case DialogResult.No:
                        _needSave = false;
                        result = true;
                        break;
                    //单击了Cancel按钮
                    case DialogResult.Cancel:
                        result = false; //返回false，通知调用本方法的程序，本次操作取消
                        break;
                }
            }

            return result;
        }

        private void RichTextBox1_TextChanged(object sender, EventArgs e)
        {
            _needSave = true;
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!SaveOldFile())
                e.Cancel = true; //不退出，程序继续运行
        }

        #endregion

        private void RichTextBox1_MouseClick(object sender, MouseEventArgs e)
        {
            try
            {
                _str = richTextBox1.SelectedText;

                if (_str != "")
                {
                    if (radioAdd.Checked)
                        _str = AddSign(_str);
                    else if (radioRemove.Checked)
                        _str = RemoveSign(_str);
                    else if (radioReverse.Checked)
                        _str = Reverse(_str);
                    else if (radioOrder.Checked)
                        _str = Order(_str);
                    else if (radioRemoveOrder.Checked)
                        _str = RemoveOrder(_str);
                    else if (radioSplit.Checked)
                        _str = CutOff(_str);

                    richTextBox1.SelectedText = _str;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"{ex}");
            }
        }

        /// <summary>
        /// 截断字符串;
        /// </summary>      
        private string CutOff(string str)
        {
            string result = string.Empty;
            string splitStr = comboBox_SplitStr.Text;
            int len = splitStr.Length;

            List<string> ls = CreateSelectList(str);

            foreach (string s in ls)
            {
                if (!string.IsNullOrWhiteSpace(s))
                {
                    int index = s.IndexOf(splitStr);
                    if (-1 == index)
                    {
                        result += s + "\r\n";
                        continue;
                    }

                    if (radioSplitLeft.Checked)
                    {
                        result += s.Substring(index + len) + "\r\n";
                    }
                    else
                    {
                        result += s.Substring(0, index) + "\r\n";
                    }
                }
            }

            return result;
        }

        /// <summary>
        /// 移除序号;
        /// </summary>
        private string RemoveOrder(string str)
        {
            radioSplitLeft.Checked = true; //设为截掉符号左边;
            return CutOff(str);
        }

        /// <summary>
        /// 添加序号;
        /// </summary>      
        private string Order(string str)
        {
            string result = string.Empty;

            string numStr = comboBox_StartNum.Text;
            bool isNum = int.TryParse(numStr, out int startNum);
            if (!isNum)
            {
                throw new Exception("请填写正确的起始序号");
            }

            int numPad = numStr.Length;
            string splitStr = comboBox_SplitStr.Text;

            List<string> ls = CreateSelectList(str);

            foreach (string s in ls)
            {
                if (!string.IsNullOrWhiteSpace(s))
                {
                    result += startNum.ToString().PadLeft(numPad, '0') + splitStr + s + "\r\n";
                    startNum++;
                }
            }

            return result;
        }

        /// <summary>
        /// 行数逆转;
        /// </summary>
        private string Reverse(string str)
        {
            string result = "";
            List<string> ls = CreateSelectList(str);

            ls.Reverse();
            foreach (string s in ls)
            {
                if (s != "")
                    result += s + "\r\n";
            }

            return result;
        }

        /// <summary>
        /// 添加符号;
        /// </summary>
        private string AddSign(string str)
        {
            bool b = LastIsLB(str);
            if (radio1.Checked)
            {//单次模式；                  
                if (b)
                    str = RemoveLineBreak(str);
                str = _signLeft + str + _signRight;
            }
            else if (radio2.Checked)
            {//多行模式；
                str = _signLeft + str;
                if (!b)
                    str = str + _signRight;
                else
                    str = str.Substring(0, str.Length - 1) + _signRight;
                str = LineBreakToSign(str);
            }
            if (b)
                str = str + (char)10;

            return str;
        }

        /// <summary>
        /// 移除符号;
        /// </summary>
        private string RemoveSign(string str)
        {
            str = str.Replace(_signLeft, "");
            str = str.Replace(_signRight, "");

            return str;
        }

        private List<string> CreateSelectList(string str)
        {
            string[] ss = str.Replace("\r", "").Split('\n');
            List<string> ls = ss.ToList<string>();
            return ls;
        }

        /// <summary>
        /// 最后是换行;
        /// </summary>   
        private bool LastIsLB(string str)
        {
            bool hasLB = false;
            if (str.LastIndexOf((char)10) == str.Length - 1)
                hasLB = true;
            return hasLB;
        }

        /// <summary>
        /// 去除所有的换行;
        /// </summary>
        private string RemoveLineBreak(string str)
        {
            char[] strArr = str.ToCharArray();
            string newStr = "";
            foreach (char cr in strArr)
            {
                if (cr == (char)10)
                {
                    continue;
                }
                newStr += cr.ToString();
            }
            return newStr;
        }

        /// <summary>
        /// 换行左右加符号;
        /// </summary>
        private string LineBreakToSign(string str)
        {
            char[] strArr = str.ToCharArray();
            string newStr = "";
            for (int i = 0; i < strArr.Length; i++)
            {
                if (strArr[i] == (char)10)
                {
                    newStr += _signRight + strArr[i] + _signLeft;
                    continue;
                }
                newStr += strArr[i];
            }
            return newStr;
        }

        private void ComboBox_TextChanged(object sender, EventArgs e)
        {
            InitComboBox();
        }

        /// <summary>
        /// 添加或移除模式的radio被选中时，其它控件的可用状态变化;
        /// </summary>
        private void RadioCheckedChanged(object sender, EventArgs e)
        {
            if (radioAdd.Checked)
            {
                comboBox_add.Enabled = true;
                radio1.Enabled = true;
                radio2.Enabled = true;
            }
            if (!radioAdd.Checked)
            {
                comboBox_add.Enabled = false;
                radio1.Enabled = false;
                radio2.Enabled = false;
            }
            if (radioRemove.Checked)
            {
                comboBox_remove.Enabled = true;
            }
            if (!radioRemove.Checked)
            {
                comboBox_remove.Enabled = false;
            }

            if (!radioOrder.Checked)
            {
                comboBox_StartNum.Enabled = false;
                comboBox_SplitStr.Enabled = false;
            }
            if (!radioRemoveOrder.Checked)
            {
                comboBox_SplitStr.Enabled = false;
            }
            if (radioOrder.Checked)
            {
                comboBox_StartNum.Enabled = true;
                comboBox_SplitStr.Enabled = true;
            }
            if (radioRemoveOrder.Checked)
            {
                comboBox_SplitStr.Enabled = true;
            }

            if (radioSplit.Checked)
            {
                groupBox_SplitType.Enabled = true;
                comboBox_SplitStr.Enabled = true;
            }
            if (!radioSplit.Checked)
            {
                groupBox_SplitType.Enabled = false;
            }

            InitComboBox();
        }

        /// <summary>
        /// 是否置顶的状态发生变化
        /// </summary>
        private void CbIsTopMost_CheckedChanged(object sender, EventArgs e)
        {
            CheckIsTopMost();
        }

        /// <summary>
        /// 检查并设置是否置顶
        /// </summary>
        private void CheckIsTopMost()
        {
            TopMost = CbIsTopMost.Checked;
        }
    }
}
